/**
 *  文本模型
 *  存储当前编辑内容，提供 API 能够对当前内容进行一些操作和修改
 */

import EventEmitter from "events";

export class TextModel extends EventEmitter {
    private spacers_ = '' //当前需要展示的内容
    constructor() {
        super()
    }

    textChangeEmit_() {
        this.emit('text-change');
    }
    // 获取当前选中的内容
    getSpacers() {
        return this.spacers_
    }

    getSpacersByIndex(startIndex: number, endIndex: number): string {
        return this.spacers_.slice(startIndex, endIndex);
    }

    // 出入内容
    insert(spacerIndex: number, spacers: string) {
        const oldSpacers = this.spacers_
        this.spacers_ = oldSpacers.slice(0, spacerIndex) + spacers + oldSpacers.slice(spacerIndex)
        this.textChangeEmit_()
    }

    remove(startIndex: number, endIndex: number) {
        const oldSpacers = this.spacers_
        if (startIndex > endIndex) {
            [startIndex, endIndex] = [endIndex, startIndex]
        }
        this.spacers_ = oldSpacers.slice(0, startIndex) + oldSpacers.slice(endIndex)
        this.textChangeEmit_()
    }
}

export default TextModel